<template>
  <div>
    <KDialog v-model:showDialog="deleteHomework.show">
      <template #header>
        <div style="font-size: 20px; font-family: 'Roboto Slab', serif">
          删除作业 DEL
        </div>
      </template>
      <div align="center">
        <div style="font-size:18px;margin:30px 10px;">你确定要删除作业吗？</div>
        <div align="right">
          <button
            class="button primary"
            style="margin: 0 10px"
            @click="deleteHomework.handleConfirm"
          >
            确定
          </button>
          <button @click="deleteHomework.show = false" style="margin: 0 10px">
            取消
          </button>
        </div>
      </div>
    </KDialog>

    <!-- 修改信息的对话框 -->
    <KDialog v-model:showDialog="adjustHomework.show" width="50%">
      <template #header>
        <div style="font-size: 20px; font-family: 'Roboto Slab', serif">
          修改作业 ADJUST
        </div>
      </template>
      <div>
        <el-scrollbar height="600px">
          <adjust 
          v-if="adjustHomework.show" 
          :homeworkID="adjustHomework.homeworkID"
          @update="updateData"
          >
          </adjust>
        </el-scrollbar>
      </div>
    </KDialog>

    <!-- 查看作业提交情况 -->
    <KDialog v-model:showDialog="querySubmitHomework.show" width="50%">
      <template #header>
        <div style="font-size: 20px; font-family: 'Roboto Slab', serif">
          提交情况 SUBMIT
        </div>
      </template>
      <div>
        <el-scrollbar height="600px">
          <submission v-if="querySubmitHomework.show" :homeworkID="querySubmitHomework.homeworkID">
          </submission>
        </el-scrollbar>
      </div>
    </KDialog>

    <section>
      <br />
      <KTitle3>我发布的作业 published</KTitle3>
      <div v-if="createdHomework.homework_num == 0" style="min-height: 1000px;">
        <el-empty description="你貌似还没有发布作业" :image-size="200" />
      </div>
      <div v-else style="min-height: 1100px">
        <div
          v-for="c in createdHomework.homework"
          :key="c.id"
        >
          <KCard style="margin: 40px; color: black">
            <template #header>
              <div style="display:flex;justify-content: space-between;}">
                <div
                  class="MyFont"
                  style="font-size: 22px; padding: 20px 10px 0px"
                >
                <span style="background-color:var(--mainColor);color:white;padding:8px;border-radius:.5em;">HW</span> 
                &ensp; {{ c.name }}
                </div>
                <div>

                <el-tooltip
                content="下载所有成员的提交结果"
                placement="top"
                effect="dark"
                >
                <button
                  style="
                    font-size: 12px;
                    margin: 20px 10px 0;
                    border-radius: 1.5em;
                  "
                  class="icon primary solid fa-download"
                  @click="exportHomework.handle(c.id)"
                >
                  下载全部
                </button>
                </el-tooltip>

                
                <button
                  style="
                    font-size: 12px;
                    margin: 20px 10px 0;
                    border-radius: 1.5em;
                  "
                  class="icon solid fa-table"
                  @click="querySubmitHomework.querySubmit(c.id)"
                >
                  提交情况
                </button>
  

                <el-tooltip
                content="修改作业的各项信息"
                placement="top"
                effect="dark"
                >
                <button
                  style="
                    font-size: 12px;
                    margin: 20px 10px 0;
                    border-radius: 1.5em;
                  "
                  class="icon primary solid fa-pen"
                  @click="adjustHomework.adjust(c.id)"
                >
                  修改
                </button>
                </el-tooltip>
                  
                <el-tooltip
                  content="小心！这部操作会删除这个作业，不过时而应该高兴"
                  placement="top"
                  effect="dark"
                >
                  <button
                    style="
                      font-size: 12px;
                      margin: 20px 10px 0;
                      border-radius: 1.5em;
                    "
                    class="icon solid fa-trash-alt"
                    @click="deleteHomework.delete(c.id)"
                  >
                    删除
                  </button>
                </el-tooltip>
                
                
                </div>
              </div>
            </template>
            <div class="MyFont" style="font-size: 16px; padding: 10px">
              <p class="icon solid fa-id-card">&ensp;作业ID: {{ c.id }}</p>
              <p class="icon solid fa-leaf">&ensp;提交类型: {{ c.type }}</p>
              <p class="icon solid fa-closed-captioning">
                &ensp;作业描述:
                {{ c.desc ? `「${c.desc}」` : "无"}}
              </p>
              <p class="icon solid fa-dragon">
                &ensp;所属学科:
                {{ c.subject }}
              </p>
              <p class="icon solid fa-hourglass-start">
                &ensp;创建时间:
                {{ makePrettyTime(c.CreatedAt) }}
              </p>
              <p class="icon solid fa-stopwatch">
                &ensp;结束时间:
                {{ makePrettyTime(c.endtime) }}
              </p>
              <p class="icon solid fa-book-dead">
                &ensp;{{ c.CanSubmitAfterEnd ? "" : "不" }} 允许在结束后提交
              </p>
              <p class="icon solid fa-object-group">
                &ensp;所属小组 ID:
                {{ c.GroupID }}
              </p>
            </div>
          </KCard>
        </div>
      </div>
    </section>
    <br />
    <section
      v-if="createdHomework.homework_num > 0"
      align="center"
      style="font-family: 'Roboto Slab', serif"
    >
      <KPagination
        v-model:cur_page="createdHomework.cur_page"
        :total="createdHomework.total_pages"
        @click="createdHomework.move"
      ></KPagination>
    </section>
  </div>
</template>

<script>
import { reactive, watch, onMounted, computed } from "vue";
import { ElNotification, ElLoading } from "element-plus"
import { useStore } from "vuex"
import { makePrettyTime } from "@/hook/format"
import adjust from "@/pages/MyHomeWorkCreate/adjust"
import submission from "@/pages/MyHomeWorkCreate/submission"
import { useRouter } from "vue-router"

export default {
  name: "MyHomeWorkCreate",
  components : {
    adjust, 
    submission
  },
  setup() {
    let store = useStore()
    let router = useRouter()

    function updateData() {
      const loading = ElLoading.service({
        lock: true,
        text: '正在拉起您的信息中...',
        background: 'rgba(0, 0, 0, 0.8)',
        customClass: "MyLoading"
      })
      store.dispatch("homeworkCreatedNum").then(function () {
        if (store.state.homework.homeworkCreatedNum) {
          // 开始根据作业数量请求最多三条，这个时候createdHomework对象已经初始化完成
          // 我们已经知道第一页需要显示的条目的index范围
          let queryIndice = createdHomework.cur_page_index
          let start = queryIndice[0];
          // let end = Math.min(store.state.homework.homeworkCreatedNum, 100);
          let end = queryIndice[queryIndice.length - 1] + 1
          // 最后一条需要在总条目之内
          end = Math.min(end, store.state.homework.homeworkCreatedNum)
          // 最后一条需要在100条请求条目之内
          end = Math.min(end, start + 100)
          store.dispatch("homeworkCreated", { start, end }).then(function () {
            loading.close()        
            if (store.state.homework.homeworkCreated.length > 0) {} 
            else {ElNotification({title: "Oops", message: "拉去初始化列表失败，错误信息: " + store.state.error})}
          });
        } 
        else {
          loading.close()
          let message
          if (store.state.homework.homeworkCreatedNum == 0) {
            ElNotification({title: "现在没有已布置的作业"})
            return
          }
          else {
            message = "不知道为啥，请求您创建的作业数量时出错了，错误信息: " + store.state.error
          }
          ElNotification({title: "Oops", message: message});
          return;
        }
      });
    }

    onMounted(updateData);

    let createdHomework = reactive({
      item_num : 10, // 如果需要修改每页显示的条目数量，修改这里
      homework: computed(() => store.state.homework.homeworkCreated),
      homework_num: computed(() => store.state.homework.homeworkCreatedNum),
      total_pages: computed(() => Math.ceil(createdHomework.homework_num / createdHomework.item_num)),
      cur_page: 1,
      last_page : undefined,
      cur_page_index: computed(() => {
        let indexes = [], start = (createdHomework.cur_page - 1) * createdHomework.item_num;
        for ( let i = start; i < Math.min(start + createdHomework.item_num, createdHomework.homework_num); ++ i) {
          indexes.push(i);
        }

        return indexes;
      }),
      // 翻页
      move() {
        if ( createdHomework.last_page != createdHomework.cur_page)
          updateData()
        createdHomework.last_page = createdHomework.cur_page
      }
    });

    let deleteHomework = reactive({
      show: false,
      homeworkID : undefined,
      delete(homeworkID) {
        deleteHomework.homeworkID = parseInt(homeworkID)
        deleteHomework.show = true
      },
      handleConfirm() {
        const loading = ElLoading.service({
          lock: true,
          text: '正在删除中...',
          background: 'rgba(0, 0, 0, 0.8)',
          customClass: "MyLoading"
        })
        store.dispatch("delHomework", {homeworkID : deleteHomework.homeworkID}).then(function() {
          if (store.state.opSuccess === true) {
            store.state.opSuccess = undefined
            // 删除后进行刷新
            store.dispatch("homeworkCreatedNum").then(function () {
              loading.close()
              if (store.state.homework.homeworkCreatedNum) {
                let start = 0;
                let end = Math.min(store.state.homework.homeworkCreatedNum, 100);
                store.dispatch("homeworkCreated", { start, end }).then(()=>{loading.close()})
                deleteHomework.show = false
                ElNotification({title : "删除成功！", message: "呼～终于结束掉了一个作业了"})
                updateData()
            }})
          }
          else {
            ElNotification({title: "Oops", message:"删除失败，原因如下：" + store.state.error})
            loading.close()
          }
        })
      }
    });

    let adjustHomework = reactive({
      show : false,
      homeworkID : undefined,
      adjust(homeworkID) {
        adjustHomework.homeworkID = parseInt(homeworkID)
        adjustHomework.show = true
      }
    })

    let querySubmitHomework = reactive({
      show : false,
      homeworkID : undefined,
      querySubmit(homeworkID) {
        querySubmitHomework.homeworkID = parseInt(homeworkID)
        querySubmitHomework.show = true
      }
    })


    let exportHomework = reactive({
      handle(homeworkID) {
        homeworkID = parseInt(homeworkID)
        store.state.export.done = false
        store.state.export.queryTime = 0

        store.state.export.queryTime += 1
        const loading = ElLoading.service({
          lock: true,
          text: '正在拼命拼命打包中, 轮询次数：' + store.state.export.queryTime,
          background: 'rgba(0, 0, 0, 0.8)',
          customClass: "MyLoading"
        })

        store.dispatch("exportAll", { homeworkID })
        let timer = setInterval(() => {
          if (store.state.export.done) {
            loading.close()
            clearInterval(timer)
            return
          }
          if (store.state.export.queryTime > 10) {
            loading.close()
            ElNotification({title: "Oops", message: "轮询次数超出上限，可能是服务器的问题，也可能是网络的问题"})
            return
          }

          store.state.export.queryTime += 1
          loading.setText('正在拼命拼命打包中, 轮询次数：' + store.state.export.queryTime)
          store.dispatch("exportAll", { homeworkID })
        }, 3000)
      }
    })

    watch(() => [store.state.export.token], () => {
      if (store.state.export.token != undefined) {
        const loading = ElLoading.service({
          lock: true,
          text: '正在拼命拼命打包中, 轮询次数：' + store.state.export.queryTime,
          background: 'rgba(0, 0, 0, 0.8)',
          customClass: "MyLoading"
        })
        let url = "https://" + window.location.host + "/api/download?token=" + store.state.export.token
        window.open(url)
        store.state.export.token = undefined
        loading.close()
      }
    })

    return {
      createdHomework,
      deleteHomework,
      makePrettyTime,
      adjustHomework,
      exportHomework,
      querySubmitHomework,
      updateData
    }
  },
};
</script>

<style>
</style>